﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Reflection;

namespace Fotobanka
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {

        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            //Zaklad url rewritingu
            /*if (Request.Url.AbsoluteUri.IndexOf(".") == -1)
            {
                HttpContext.Current.RewritePath("~" + Request.Url.AbsolutePath + ".aspx");
            } else {
                if (Request.Url.AbsolutePath.IndexOf(".aspx") != -1)
                {
                    Response.Redirect(Request.Url.AbsolutePath.Remove(Request.Url.AbsolutePath.IndexOf(".aspx")));
                }            
            }*/

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            
        }

        protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
        {
            HttpSessionState session = HttpContext.Current.Session;
            if (session != null)
            {
                LoginInfo li = (LoginInfo)Session["logged_user_id"];

                if (li == null)
                {
                    if (Utils.IsPageInMembersArea(Request.Path.Substring(1))) //je stranka v seznamu stranek, kde je potreba prihlaseni?
                    {
                        Response.Redirect("AccessRestricted.aspx", true);
                    }
                } else {
                    if (!Utils.CanAccess(Request.Path.Substring(1), li.Role)) //ma tato role pristup na stranku?
                    {
                        Response.Redirect("AccessRestricted.aspx", true);
                    }
                }
            }
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            //presmerovani na error page
            Exception exception = Server.GetLastError();
            HttpException httpException = (HttpException)exception;

            if (httpException.GetHttpCode() == 404)
                Response.Redirect("Error404.aspx", true);
        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}